package com.better517na.stateprocess.state.impl;

import com.better517na.stateprocess.model.ServiceResult;
import com.better517na.stateprocess.model.StateContext;
import com.better517na.stateprocess.state.StateActionStep;
import com.better517na.stateprocess.state.StateProcessor;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public abstract class AbstractStateProcessor<T,C> implements StateProcessor<T, C>, StateActionStep<T, C> {

    private Logger logger;

    @Override
    public final ServiceResult<T> action(StateContext<C> context) throws Exception {

        ServiceResult<T> result = null;
        try {
            //数据校验测试
            //数据校验
            this.check(context);
            // 数据准备
            this.prepare(context);

            //本次处理加锁校验
            this.isLock(context);

            // getNextState不能在prepare前，因为有的nextState是根据prepare中的数据转换而来
            String nextState = this.getNextState(context);

            // 业务逻辑
            result = this.action(nextState, context);
            if (!result.getSuccess()) {
                return result;
            }
            // 持久化
            result = this.save(nextState, context);
            if (!result.getSuccess()) {
                return result;
            }
            // 后续处理
            this.after(context);

            return result;

        }catch (Exception e){
            logger.error("状态机流转处理异常！");
        }
        return result;
    }
}
